The maximum sum subarray problem consists in finding the maximum sum of a contiguous >subsequence in an array or list of integers:
max_sequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])
# should be 6: [4, -1, 2, 1]
Easy case is when the list is made up of only positive numbers and the maximum sum is >the sum of the whole array. If the list is made up of only negative numbers, return 0 >instead.
Empty list is considered to have zero greatest sum. Note that the empty list or array >is also a valid sublist/subarray.
題目理解:給定一個元素皆為數字的列表arr,找到該列表所有連續組合中最大總和,並返還該總和。如果列表內皆為負數或為空列表,則返還0。
所有的連續子集合必存在起始索引位置i&結束位置索引k,故需利用巢狀迴圈找出所有i&k匹配組合,取其sum(arr[i:k])值最大者。
def max_sequence(arr):
#若為空集合則返還0
if arr == []:
return 0
all_sum = []
#第一層for迴圈遍歷所有起始索引i的可能性
for i in range(len(arr)):
#第二層for迴圈遍歷所有結束索引k的可能性
for k in range(len(arr)):
#若k<i則該子即視作[]故不影響計算,須留意list[a:b]僅包含到b-1,故需+1
all_sum.append(sum(arr[i:k+1]))
#若最大和小於0,代表arr內皆為負數故返還0
if max(all_sum)<0:
return 0
return max(all_sum)